using Microsoft.VisualStudio.Modeling;

namespace Microsoft.Modeling.StoryboardDesigner
{
    /// <summary>
    /// Rule to update compartments when an item is added to the list
    /// </summary>
    [RuleOn(typeof(StoryboardHasElements), FireTime = TimeToFire.TopLevelCommit, InitiallyDisabled = false)]
    internal sealed class ScenarioShapeCompartmentItemAddRule : AddRule
    {
        /// <summary>
        /// Called when an element is added. 
        /// </summary>
        /// <param name="e"></param>
        public override void ElementAdded(ElementAddedEventArgs e)
        {
            if(e.ModelElement.IsDeleted)
            {
                return;
            }

            if(e.ModelElement.Store.TransactionManager.CurrentTransaction.IsSerializing)
            {
                return;
            }

            StoryboardHasElements link = e.ModelElement as StoryboardHasElements;

            if(link == null || link.StoryboardElement == null)
            {
                return;
            }

            Scenario mel = link.StoryboardElement as Scenario;

            if(mel != null)
            {
                CompartmentHelper.UpdateCompartments(mel,
                    typeof(ScenarioShape),
                    ScenarioShape.ActionCompartmentName,
                    false);
            }
        }
    }

    /// <summary>
    /// Rule to update compartments when the property on an item being displayed changes.
    /// </summary>
    [RuleOn(typeof(Scenario), FireTime = TimeToFire.TopLevelCommit, InitiallyDisabled = false)]
    internal sealed class ScenarioShapeCompartmentItemChangeRule : ChangeRule
    {
        /// <summary>
        /// Called when an element is changed
        /// </summary>
        /// <param name="e"></param>
        public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
        {
            ElementPropertyChanged(e, false);
        }

        internal static void ElementPropertyChanged(ElementPropertyChangedEventArgs e, bool repaintOnly)
        {
            if(e.ModelElement.Store.TransactionManager.CurrentTransaction.IsSerializing)
            {
                return;
            }

            if(e.ModelElement is Scenario)
            {
                if(e.DomainProperty.Id == Scenario.ActionDomainPropertyId)
                {
                    CompartmentHelper.UpdateCompartments(
                        e.ModelElement as Scenario,
                        typeof(ScenarioShape),
                        ScenarioShape.ActionCompartmentName,
                        repaintOnly);
                }
            }
        }
    }
}